package com.mmall.service.impl;

import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUerService;
import com.mmall.util.MD5Util;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.ServerSocket;
import java.util.Map;
import java.util.UUID;

/**
 * @author:lzq
 * @date: 2018/3/1 18:02
 */
@Service("iUerService")
public class UserServiceImpl implements IUerService{
    @Autowired
    private UserMapper userMapper;
    public ServerResponse<User> login(String username,String password){
        int resultCount = userMapper.checkUserName(username);
        if(resultCount == 0){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        String md5_password = MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(username, md5_password);
        if(user==null){
            return ServerResponse.createByErrorMessage("密码错误");
        }
        user.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登录成功",user);
    }

    public ServerResponse register(User user){
        ServerResponse response = this.checkValid(user.getEmail(),Const.EMAIL);
        if(!response.isSuccess()){
            return response;
        }
        response = this.checkValid(user.getUsername(),Const.USERNAME);
        if(!response.isSuccess()){
            return response;
        }
        user.setRole(Const.Role.ROLE_CUSTOMER);
        //密码加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int count=userMapper.insert(user);
        if(count==0){
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createByErrorMessage("注册成功");
    }

    public ServerResponse<String> checkValid(String str,String type){
        if(StringUtils.isEmpty(type)){
            return ServerResponse.createByErrorMessage("参数错误！");
        }
        if(type.equals(Const.USERNAME)){
          int resultCount=userMapper.checkUserName(str);
          if(resultCount!=0){
              return ServerResponse.createByErrorMessage("用户名不能重复");
          }
        }
        if(type.equals(Const.EMAIL)){
            int resultCount=userMapper.checkEmail(str);
            if(resultCount!=0){
                return ServerResponse.createByErrorMessage("email已经存在！");
            }
        }
        return ServerResponse.createBySuccessMessage("参数校验成功");
    }

    public ServerResponse getQuestionByName(String username){
        ServerResponse<String> response= this.checkValid(username, Const.USERNAME);
        if(response.isSuccess()){
            return ServerResponse.createByErrorMessage("该用户不存在");
        }
        String question = userMapper.getQuestionByName(username);
        if(!StringUtils.isEmpty(question)){
            return ServerResponse.createBySuccess(question);
        }
        return ServerResponse.createByErrorMessage("该用户未设置找回密码问题");
    }

    public ServerResponse checkAnswer(String username,String answer,String question){
        int resultCount = userMapper.selectAnswer(username, answer, question);
        if(resultCount!=0){
            //生成token返回给前端
            String token= UUID.randomUUID().toString();
            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,token);
            return ServerResponse.createBySuccess(token);
        }
        return ServerResponse.createByErrorMessage("答案错误");
    }

    public ServerResponse forgetResetPassword(String username,String passwordNew,String token){
        if(StringUtils.isEmpty(token)){
            ServerResponse.createByErrorMessage("参数错误，需要传递token");
        }
        String old_token = TokenCache.getKey(TokenCache.TOKEN_PREFIX + username);
        //判断token是否过期
        if(StringUtils.isEmpty(old_token)){
            ServerResponse.createByErrorMessage("token无效或者已过期，请重新验证");
        }
        if(StringUtils.equals(token,old_token)){
            String md5_password=MD5Util.MD5EncodeUtf8(passwordNew);
            //根据用户名更新password
            int resultCount = userMapper.updatePasswordbyUsername(username, md5_password);
            if(resultCount>0){
                return ServerResponse.createBySuccessMessage("密码更新成功");
            }
        }else{
            return ServerResponse.createBySuccessMessage("token失效请重新获取token");
        }
        return  ServerResponse.createByErrorMessage("密码更新失败");
    }

    public ServerResponse resetPassword(String passwordOld,String passwordNew,User user){
        //检测用户的旧密码是否正确
        ServerResponse<User> response = this.login(user.getUsername(), passwordOld);
        User old_user = response.getData();
        if(old_user==null){
            return ServerResponse.createByErrorMessage("旧密码错误");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        int resultCount = userMapper.updateByPrimaryKey(user);
        if(resultCount>0){
            return ServerResponse.createBySuccessMessage("密码更新成功");
        }
        return ServerResponse.createByErrorMessage("密码更新失败");
    }

    public ServerResponse<User> updateInformation(User user){
        //检测email是否存在
        int resultCount = userMapper.checkEmailByid(user.getEmail(), user.getId());
        if(resultCount>0){
            return ServerResponse.createByErrorMessage("email已经存在，请更换email");
        }
        User new_user=new User();
        new_user.setPhone(user.getPhone());
        new_user.setQuestion(user.getQuestion());
        new_user.setAnswer(user.getAnswer());
        user.setId(user.getId());
        int count = userMapper.updateByPrimaryKeySelective(user);
        if(count>0){
            return ServerResponse.createBySuccess("用户信息更新成功",user);
        }
        return ServerResponse.createByErrorMessage("用户信息更新失败");
    }

    public ServerResponse<User> getInformation(int userid){
        User user = userMapper.selectByPrimaryKey(userid);
        if(user==null){
            return ServerResponse.createByErrorMessage("该用户未登录，请登录");
        }
        return ServerResponse.createBySuccess("用户信息获取成功",user);
    }

    //backend
    public  ServerResponse checkAdmin(User user){
        if(user !=null && user.getRole().intValue()==Const.Role.ROLE_ADMIN){
            return  ServerResponse.createBySuccess();
        }
        return  ServerResponse.createByError();
    }
}
